<template>
  <div class="app-container">
    <van-nav-bar title="" left-arrow @click-left="$emit('back')" />
    <div class="title-box">
      <div class="title">保险经纪人</div>
      <div class="tip">保险推荐</div>
    </div>
    <div class="main-box" ref="resultBoxRef">
      <!-- <el-scrollbar ref="scrollbarRef"> -->
      <el-card class="card my-info" shadow="never" v-loading="!countPersonaInsuranceTotal.value">
        <div class="handle-box">
          <div class="user-list">
            <span class="user">{{ nickname || '小智' }}</span>
          </div>
          <div class="family">
            <svg-icon icon-class="add" />为家人定制
          </div>
        </div>
        <div class="info-box">
          <div class="avatar-box">
            <div class="avatar" />
            <div class="my-base">
              <div class="name">{{ nickname }}</div>
              <div class="link">已有保单 {{ countPersonaInsuranceTotal.value }} ></div>
            </div>
          </div>
          <div class="my-claims">
            <div class="amount-box">
              <div class="label">已有保障赔付金额</div>
              <div class="value">{{ countPersonaInsuranceTotal.totalAmount }}万</div>
            </div>
            <div class="calculation-btn disable">
              理赔测算
            </div>
            <!-- <div class="calculation-btn" @click="$router.push('/AiBenefitAssociation/CompensationPay-out')">
                理赔测算
              </div> -->
          </div>
        </div>
      </el-card>
      <el-card class="card insurance-data" shadow="never" v-loading="!countPersonaInsuranceTotal.value">
        <div class="chart-box">
          <chart class="chart" :chart-option="radar_chartOpt" :auto-resize="true" height="100%" />
        </div>
        <div class="insurance-box">
          <div class="legend-box">
            <div class="legend-item full-protection">足额保障</div>
            <div class="legend-item partial-protection">部分保障</div>
            <div class="legend-item not-protection">未保障</div>
          </div>
          <div class="insurance-item" v-for="item in countPersonaInsuranceData" :key="item.name"
            :class="item.totalAmount >= item.maxAmount ? 'full' : item.totalAmount ? 'partial' : 'not'"
            @click="showInsuranceEditDialog(item.name)">
            <div class="icon" />
            <div class="text-box">
              <div class="label">
                <span>{{ item.name }}</span>
              </div>
              <div class="value">
                <span v-if="item.value">{{ `保障${item.totalAmount}万元` }}</span>
                <span v-else>未保障</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>
      <el-card class="card insurance-recommend" shadow="never">
        <div class="card-title">
          <div class="title">保险推荐</div>
        </div>
        <div class="content-box">
          <div class="result-box" v-loading="!msgList.length">
            <!-- <div class="analyze-box">
              <el-collapse class="analyze-process" v-model="analyzeProcessCollapse" accordion>
                <el-collapse-item name="analyze-process">
                  <template slot="title">
                    <div class="title">
                      <svg-icon icon-class="analyze" />
                      <span>保险库对比分析</span>
                      <span class="analyze-loading">
                        <span v-if="!msgList.length">思考中 <i class="el-icon-loading" /></span>
                        <span v-else>已深度思考</span>
                      </span>
                    </div>
                  </template>
                  <div class="analyze-result process">
                    <div class="content" ref="analyzeProcessRef">
                      <div class="row" v-for="row in analyzeProcessList">
                        {{ row.content }}
                      </div>
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
              <div class="analyze-result" v-show="analyzeResultList.length">
                <div class="content" ref="analyzeResultRef">
                  <div class="row" v-for="row in analyzeResultList">
                    {{ row.content }}
                  </div>
                </div>
              </div>
            </div> -->
            <div class="chat-box">
              <div class="msg-row" :class="msg.role == 'user' && 'right'" v-for="(msg, index) in msgList" :key="index">
                <div class="user-info">
                  <img class="avatar" :src="require(`@/assets/images/insuranceRecommend/${msg.role}_avatar.png`)" />
                </div>
                <div class="content" :class="msg.role">
                  <div class="content-data" v-if="msg.content">
                    <!-- 温馨提示 -->
                    <span class='tip' v-if="msg.tip">
                      <svg-icon icon-class="warning" /> {{ msg.tip }}
                    </span>
                    <!-- 文本 -->
                    <span class="text">{{ msg.content }}</span>
                    <!-- 表格 -->
                    <el-table class="table" v-if="msg.tableColumn" :data="msg.tableData" :show-header="true" stripe>
                      <el-table-column v-for="item in msg.tableColumn" :key="item.prop" :label="item.label"
                        :prop="item.prop" :class-name="item.className" :width="item.width" :min-width="item.minWidth"
                        :sortable="item.sortable" :align="item.align" :show-overflow-tooltip="item.showOverflowTooltip"
                        :resizable="false" />
                    </el-table>
                    <!-- 保险对比 -->
                    <div class="insurance-compare-box" v-if="msg.insuranceCompareData">
                      <div class="compare-row" v-for="compareItem in msg.insuranceCompareData">
                        <!-- <div class="compare-title">{{ key }}</div> -->
                        <div class="compare-content">
                          <div class="insurance-box" v-for="(product, index) in compareItem.comparison_product"
                            :key="product.insuranceName">
                            <div class="insurance-item" @click="showInsuranceDetailDialog(product)">
                              <div class="base-info">
                                <div class="img-box"></div>
                                <div class="text-box">
                                  <div class="name">{{ product.insuranceName }}</div>
                                  <div class="company-name">{{ product.companyName }}</div>
                                  <div class="price" v-show="product.insuredAmount">{{ product.insuredAmount }} 元</div>
                                </div>
                              </div>
                              <div class="more-info">
                                <div class="info-item">
                                  <div class="value">{{ product.protectionAmount }}</div>
                                  <div class="label">保额</div>
                                </div>
                                <div class="info-item">
                                  <div class="value">{{ product.supportPeriod }}</div>
                                  <div class="label">保障范围</div>
                                </div>
                                <div class="info-item">
                                  <div class="value">{{ product.guaranteeObject }}</div>
                                  <div class="label">保障对象</div>
                                </div>
                              </div>
                            </div>
                            <div class="compare-tip" v-for="(data, key) in compareItem.dimensions">
                              <div class="title">{{ key }}</div>
                              <div class="text" v-for="text in data[product.dimensionsProp] || []">{{ text }}
                              </div>
                            </div>
                            <div class="vs" v-if="index== 0">VS</div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <!-- 推荐方案 -->
                    <div class="solution-box" v-if="msg.solutionData">
                      <div class="tab-box">
                        <div class="tab-item" v-for="(item, index) in msg.solutionData" :key="item.insuranceName"
                          :class="index == msg.activeSolutionIndex && 'active'"
                          @click="msg.activeSolutionIndex = index">
                          {{ item.insuranceName }}
                        </div>
                      </div>
                      <div class="solution-content-box">
                        <div class="title-box">
                          <div class="company-name">{{ msg.solutionData[msg.activeSolutionIndex].companyName }}</div>
                          <div class="amount" v-show="msg.solutionData[msg.activeSolutionIndex].insuredAmount">
                            保费：<span class="num">{{ msg.solutionData[msg.activeSolutionIndex].insuredAmount }}</span>
                            元
                          </div>
                        </div>
                        <div class="data-box">
                          <template v-if="JSON.stringify(msg.solutionData[msg.activeSolutionIndex].details) != '{}'">
                            <div class="data-item"
                              v-for="(data, key) in msg.solutionData[msg.activeSolutionIndex].details" :key="key">
                              <div class="data-title">{{ solutionTitleKeyObj[key] }}</div>
                              <template v-if="Array.isArray(data)">
                                <div class="data" v-for="dataItem in data">
                                  {{ dataItem }}
                                </div>
                              </template>
                              <template v-else>
                                <div class="data-children" v-for="(childData, childKey) in data" :key="childKey">
                                  <template v-if="Array.isArray(childData)">
                                    <div class="data-children-label">{{ childKey }}</div>
                                    <div class="data-children-data" v-for="childDataItem in childData">
                                      <span v-if="typeof (childDataItem) == 'string'">{{ childDataItem }}</span>
                                      <template v-else>
                                        <span v-for="(childDataItemValue, childDataItemKey) in childDataItem">
                                          {{ `${childDataItemKey}：${childDataItemValue}` }}
                                        </span>
                                      </template>
                                    </div>
                                  </template>
                                  <template v-else>
                                    <span class="data-children-label">{{ childKey }}</span>
                                    <span class="data-children-data">{{ childData }}</span>
                                  </template>
                                </div>
                              </template>
                            </div>
                          </template>
                          <template v-else>
                            <div class="empty-data">暂无数据</div>
                          </template>
                        </div>
                      </div>
                    </div>
                  </div>
                  <i v-else class="el-icon-loading" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
      <!-- </el-scrollbar> -->
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { fetchEventSource } from '@microsoft/fetch-event-source';
import * as api from '@/api/insuranceRecommend/index.js';

export default {
  name: 'InsuranceRecommend',
  props: {
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      countPersonaInsuranceTotal: {},
      countPersonaInsuranceData: [],
      countPersonaInsuranceChartData: [],
      radar_chartOpt: {},
      analyzeProcessCollapse: 'analyze-process',
      analyzeProcessList: [],
      analyzeProcessScrollOnBottom: true,
      analyzeResultList: [],
      analyzeResultScrollOnBottom: true,
      processData: { recommendInsuranceName: [] }, // 流程数据
      msgList: [],
      msgScrollOnBottom: true,
      solutionTitleKeyObj: {
        coreGuarantee: '核心保障',
        insuranceRules: '投保规则',
        healthInformationDetails: '健康告知重点',
        samplePremium: '保费保费示例（有社保）',
        mattersNeedingAttention: '注意事项',
      },
    };
  },
  computed: {
    ...mapGetters(['nickname']),
  },
  watch: {
    // // 监听分析过程列表，更新时，保持滚动条位于底部
    // analyzeProcessList: {
    //   handler(val) {
    //     this.$nextTick(() => {
    //       // 判断是否滚动在底部
    //       if (this.analyzeProcessScrollOnBottom) {
    //         if (this.$refs.analyzeProcessRef) {
    //           const ref = this.$refs.analyzeProcessRef;
    //           ref.scrollTop = ref.scrollHeight - ref.offsetHeight;
    //         }
    //       }
    //     });
    //   },
    //   deep: true,
    // },
    // // 监听分析结果列表，更新时，保持滚动条位于底部
    // analyzeResultList: {
    //   handler(val) {
    //     this.$nextTick(() => {
    //       // 判断是否滚动在底部
    //       if (this.analyzeResultScrollOnBottom) {
    //         if (this.$refs.analyzeResultRef) {
    //           const ref = this.$refs.analyzeResultRef;
    //           ref.scrollTop = ref.scrollHeight - ref.offsetHeight;
    //         }
    //       }
    //     });
    //   },
    //   deep: true,
    // },
    // 监听消息列表，更新时，保持滚动条位于底部
    msgList: {
      handler(val) {
        this.$nextTick(() => {
          // 判断是否滚动在底部
          if (this.msgScrollOnBottom) {
            if (this.$refs.resultBoxRef) {
              const ref = this.$refs.resultBoxRef;
              ref.scrollTop = ref.scrollHeight - ref.offsetHeight;
            }
          }
        });
      },
      deep: true,
    },
  },
  created() {
    this.getData();
  },
  methods: {
    // 处理滚动事件
    handleScroll() {
      // // 分析过程模块
      // const analyzeProcessRef = this.$refs.analyzeProcessRef;
      // analyzeProcessRef.addEventListener(
      //   'scroll',
      //   () => {
      //     // 用户开始滚动并在最底部之上，取消保持在最底部的效果
      //     if (analyzeProcessRef.scrollTop + analyzeProcessRef.offsetHeight + 5 < analyzeProcessRef.scrollHeight)
      //       this.analyzeProcessScrollOnBottom = false;
      //     // 用户停止滚动并滚动到最底部，开启保持到最底部的效果
      //     else this.analyzeProcessScrollOnBottom = true;
      //   },
      //   true
      // );
      // // 分析结果模块
      // const analyzeResultRef = this.$refs.analyzeResultRef;
      // analyzeResultRef.addEventListener(
      //   'scroll',
      //   () => {
      //     // 用户开始滚动并在最底部之上，取消保持在最底部的效果
      //     if (analyzeResultRef.scrollTop + analyzeResultRef.offsetHeight + 5 < analyzeResultRef.scrollHeight)
      //       this.analyzeResultScrollOnBottom = false;
      //     // 用户停止滚动并滚动到最底部，开启保持到最底部的效果
      //     else this.analyzeResultScrollOnBottom = true;
      //   },
      //   true
      // );
      // 消息列表
      const resultBoxRef = this.$refs.resultBoxRef;
      resultBoxRef.addEventListener(
        'scroll',
        () => {
          // 用户开始滚动并在最底部之上，取消保持在最底部的效果
          if (resultBoxRef.scrollTop + resultBoxRef.offsetHeight + 5 < resultBoxRef.scrollHeight)
            this.msgScrollOnBottom = false;
          // 用户停止滚动并滚动到最底部，开启保持到最底部的效果
          else this.msgScrollOnBottom = true;
        },
        true
      );
    },
    async getData() {
      this.getCountPersonaInsurance();
      await this.getInsuranceList();
      this.getAiInsurance();
    },
    // 获取用户保险
    getCountPersonaInsurance() {
      api.getCountPersonaInsuranceByInsuranceType().then(({ data }) => {
        // 用户保险数据总数
        this.countPersonaInsuranceTotal = data.shift();
        // 用户保险数据
        this.countPersonaInsuranceData = data.map((item) => {
          if (item.name == '住院综合医疗险（电信）') item.maxAmount = 600;
          if (item.name == '政府百万医保') item.maxAmount = 100;
          if (item.name == '重疾险（市场）') item.maxAmount = 200;
          if (item.name == '意外险（电信）') item.maxAmount = 220;
          if (item.name == '意外险（市场）') item.maxAmount = 600;
          item.max = 100;
          return item;
        });
        // 图表数据
        this.countPersonaInsuranceChartData = {
          seriesData: data.map((item) => {
            item.rate = Number(((item.totalAmount / item.maxAmount) * 100).toFixed(0));
            item.rate = item.rate > 100 ? 100 : item.rate;
            return item.rate;
          }),
          indicatorData: this.countPersonaInsuranceData,
        };
        this.radar_chartOpt = this.$eChartsOption.radar_basic({
          seriesData: this.countPersonaInsuranceChartData.seriesData,
          indicatorData: this.countPersonaInsuranceChartData.indicatorData,
          color: ['#0256FF'],
          radius: ['0%', '60%'],
          startAngle: 90,
          axisColor: '#3d3d3d',
          fontSize: 15,
          unit: '%',
        });
        this.radar_chartOpt.radar.splitNumber = 2;
        this.radar_chartOpt.radar.axisName.formatter = function (value, indicator) {
          return `${value}\n{a|${indicator.rate}%}`;
        };
        this.radar_chartOpt.radar.axisName.rich = {
          a: { align: 'center', fontSize: 15, padding: 5 },
        };
      });
    },
    // 获取AI保险推荐
    getAiInsurance() {
      // 添加推荐方案消息
      this.msgList.push({ role: 'robot', content: '', solutionData: [{}], activeSolutionIndex: 0 });
      // 参数
      let user_text = [];
      for (const key in this.formData) {
        const element = this.formData[key];
        if (key == 'age') user_text.push(`${element}岁`);
        if (key == 'cityName') user_text.push(element);
        if (key == 'telecomStaff') user_text.push(element);
        // if (key == 'kinship') if (element) user_text.push(element);
        if (key == 'employeeCategory') if (element) user_text.push(element);
        if (key == 'businessTrip') user_text.push(element == '是' ? '经常出差' : '不经常出差');
        if (key == 'socialSecurity') user_text.push(element == '是' ? '有购买社保' : '未购买社保');
        // if (key == 'retire') user_text.push(element == '是' ? '退休' : '在岗');
        if (key == 'criticalIllness') user_text.push(element == '是' ? '有重大疾病' : '无重大疾病');
        if (key == 'purchaseHospitalInsurance')
          user_text.push(element == '是' ? '有持续购买企业住院综合医疗险' : '未持续购买企业住院综合医疗险');
        if (key == 'backgroundDisease') element == '无' ? user_text.push('无慢性病') : user_text.push(element);
      }
      user_text = user_text.join('、');
      // 请求SSE保险推荐接口
      const that = this;
      const url = 'http://183.56.241.175:6557/api/insurance-analysis-compare'; // SSE服务的URL
      // const url = 'http://10.18.124.22:6557/api/insurance-analysis-compare'; // SSE服务的URL
      fetchEventSource(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          user_text,
        }),
        onopen(event) {
          console.log('建立连接', event);
        },
        onmessage: ({ data }) => {
          console.log('data', data);
          that.processData.recommendInsuranceName += data;
        },
        onclose: async () => {
          console.log('连接关闭');
          // 推荐方案数据处理
          that.processData.recommendInsuranceName = JSON.parse(
            that.processData.recommendInsuranceName
          ).recommendInsuranceName;
          // 推荐方案
          const solution_msgItem = that.msgList[that.msgList.length - 1];
          await that.typing(solution_msgItem, '推荐方案');
          const recommendInsuranceNameRequest = that.processData.recommendInsuranceName.map((insuranceName) => {
            const params = {
              age: that.formData.age,
              socialSecurity: that.formData.socialSecurity,
              insuranceName,
            };
            return api.selectInsuranceProduct(params).then(({ data }) => {
              if (data) {
                return {
                  insuranceName: data.insuranceName || insuranceName,
                  companyName: data.companyName || '',
                  insuredAmount: data.insuredAmount || '',
                  details: data.details ? JSON.parse(data.details) : {},
                };
              }
            });
          });
          const solutionData = await Promise.all(recommendInsuranceNameRequest);
          solution_msgItem.solutionData = solutionData;
          // 持续购买企业住院综合医疗险 为 否 时
          if (that.formData.purchaseHospitalInsurance == '否') {
            api
              .selectInsuranceProduct({ age: that.formData.age, cityName: that.formData.cityName })
              .then(({ data }) => {
                if (data) {
                  solution_msgItem.solutionData.push({
                    insuranceName: data.insuranceName || insuranceName,
                    companyName: data.companyName || '',
                    insuredAmount: data.insuredAmount || '',
                    details: data.details ? JSON.parse(data.details) : {},
                  });
                }
              });
          }
        },
        onerror(event) {
          console.log('连接错误', event);
        },
      });
    },
    // 获取保险推荐
    async getInsuranceList() {
      // 请求保险对比
      const { data } = await api.getComparisonInfo();
      this.processData.accidentInsurance_tableColumn = [
        { label: '产品名称', prop: 'product_name' },
        { label: '保险公司', prop: 'insurance_company' },
        { label: '意外身故/伤残保额', prop: 'accidental_coverage' },
        { label: '意外医疗保额', prop: 'accidental_medical_insurance_coverage' },
        { label: '保障范围', prop: 'coverage_summary' },
        { label: '免赔额', prop: 'deductible' },
        // { label: '投保年龄', prop: 'insured_age' },
        // { label: '续保条件', prop: 'renewal_conditions' },
        { label: '健康告知要求', prop: 'health_disclosure' },
        // { label: '等待期', prop: 'waiting_period' },
        // { label: '医院范围', prop: 'hospital_range' },
        { label: '报销比例', prop: 'reimbursement_rate' },
        { label: '特点', prop: 'special_features' },
      ];
      this.processData.accidentInsurance_tableData = JSON.parse(data.accidentInsurance);
      this.processData.medicalInsurance_tableColumn = [
        { label: '产品名称', prop: 'product_name' },
        { label: '保险公司', prop: 'insurance_company' },
        { label: '一般保险金额', prop: 'general_cover_amount' },
        { label: '重大疾病保险金额', prop: 'critical_illness_cover_amount' },
        { label: '保障范围', prop: 'coverage_summary' },
        { label: '免赔额', prop: 'deductible' },
        // { label: '投保年龄', prop: 'insured_age' },
        // { label: '续保条件', prop: 'renewal_conditions' },
        { label: '健康告知要求', prop: 'health_disclosure' },
        // { label: '等待期', prop: 'waiting_period' },
        // { label: '医院范围', prop: 'hospital_range' },
        { label: '报销比例', prop: 'reimbursement_rate' },
        { label: '特点', prop: 'special_features' },
      ];
      this.processData.medicalInsurance_tableData = JSON.parse(data.medicalInsurance);
      this.processData.threeDimensionalAccidentInsurance = JSON.parse(data.threeDimensionalAccidentInsurance);
      this.processData.threeDimensionalMedicalInsurance = JSON.parse(data.threeDimensionalMedicalInsurance);
      await this.parseProcessData(this.processData);
    },
    // 处理流程数据
    async parseProcessData(processData) {
      // // 保险库对比分析 输出
      // await processData.introduction.reduce(async (pre, item) => {
      //   await pre;
      //   const length = this.analyzeResultList.push({ content: '' });
      //   return this.typing(this.analyzeResultList[length - 1], item);
      // }, Promise.resolve());
      // 温馨提示
      if (this.formData.businessTrip == '是') {
        this.msgList.push({ role: 'robot', content: '', tip: '温馨提示' });
        const tip_msgItem = this.msgList[this.msgList.length - 1];
        await this.typing(tip_msgItem, '尊敬的客户，鉴于您的场景多样化，为您的安全加双保险，现推荐您购买两份意外险');
      }
      // 医院定点温馨提示
      this.msgList.push({ role: 'robot', content: '', tip: ' 医院定点温馨提示' });
      const tip_msgItem = this.msgList[this.msgList.length - 1];
      await this.typing(tip_msgItem, '就医选择定点医院，降低自费比例、理赔更高效、健康保障更省心！');
      // 门慢政策
      if (this.formData.backgroundDisease != '无') {
        this.msgList.push({ role: 'robot', content: '', tip: '' });
        const tip_msgItem = this.msgList[this.msgList.length - 1];
        await this.typing(
          tip_msgItem,
          '掌握门慢政策=每年省数千元，了解门慢政策可拨打参保地区号+12393（医保服务热线）或通过“国家医保服务平台APP”查询'
        );
      }
      // 医疗险 重点产品对比
      this.msgList.push({ role: 'robot', content: '', tableColumn: [], tableData: [] });
      const medicalInsurance_msgItem = this.msgList[this.msgList.length - 1];
      await this.typing(medicalInsurance_msgItem, '医疗险 重点产品对比');
      medicalInsurance_msgItem.tableColumn = processData.medicalInsurance_tableColumn;
      medicalInsurance_msgItem.tableData = processData.medicalInsurance_tableData;
      // 意外险 重点产品对比
      this.msgList.push({ role: 'robot', content: '', tableColumn: [], tableData: [] });
      const accidentInsurance_msgItem = this.msgList[this.msgList.length - 1];
      await this.typing(accidentInsurance_msgItem, '意外险 重点产品对比');
      accidentInsurance_msgItem.tableColumn = processData.accidentInsurance_tableColumn;
      accidentInsurance_msgItem.tableData = processData.accidentInsurance_tableData;

      // 医疗险 推荐依据与对比分析
      this.msgList.push({ role: 'robot', content: '', insuranceCompareData: [] });
      const medicalInsuranceAnalysis_msgItem = this.msgList[this.msgList.length - 1];
      await this.typing(medicalInsuranceAnalysis_msgItem, '医疗险 推荐依据与对比分析');
      medicalInsuranceAnalysis_msgItem.insuranceCompareData = processData?.threeDimensionalMedicalInsurance || [];
      medicalInsuranceAnalysis_msgItem.insuranceCompareData = await this.parseThreeDimensional(
        medicalInsuranceAnalysis_msgItem.insuranceCompareData
      );
      // 意外险 推荐依据与对比分析
      this.msgList.push({ role: 'robot', content: '', insuranceCompareData: [] });
      const accidentInsuranceAnalysis_msgItem = this.msgList[this.msgList.length - 1];
      await this.typing(accidentInsuranceAnalysis_msgItem, '意外险 推荐依据与对比分析');
      accidentInsuranceAnalysis_msgItem.insuranceCompareData = processData?.threeDimensionalAccidentInsurance || [];
      accidentInsuranceAnalysis_msgItem.insuranceCompareData = await this.parseThreeDimensional(
        accidentInsuranceAnalysis_msgItem.insuranceCompareData
      );
    },
    // 维度对比处理
    async parseThreeDimensional(insuranceCompareData) {
      for (const compareItem of insuranceCompareData) {
        const productPromises = compareItem.comparison_product.map(async (product, index) => {
          let params = {
            age: this.formData.age,
            socialSecurity: this.formData.socialSecurity,
            insuranceName: product,
          };
          // 查询产品信息
          const { data } = await api.selectInsuranceProduct(params);
          if (!data) return { insuranceName: product };
          return {
            insuranceName: data.insuranceName,
            insuredAmount: data.insuredAmount,
            protectionAmount: data.protectionAmount,
            companyName: data.companyName,
            supportPeriod: data.supportPeriod,
            guaranteeObject: data.guaranteeObject,
            dimensionsProp: index == 0 ? 'baseline' : 'comparison',
          };
        });
        compareItem.comparison_product = (await Promise.all(productPromises)).filter((item) => item !== null);
      }
      return insuranceCompareData;
    },
    // 打字效果输出
    typing(msg, text) {
      return new Promise((resolve) => {
        let charCount = 0;
        const timer = setInterval(() => {
          if (charCount < text.length) {
            msg.content += text.charAt(charCount);
            charCount++;
          } else {
            clearInterval(timer);
            resolve(); // 解析 Promise，表示完成
          }
        }, 10);
      });
    },
    // await setTimeOut改造
    async timeOut(ms) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(ms);
        }, ms);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .van-nav-bar {
  &::after {
    content: none;
  }

  .van-icon {
    color: #fff !important;
  }
}

.title-box {
  width: calc(100% - 60px);
  padding: 15px 30px;
  padding-top: 0;
  color: #fff;
  display: flex;
  // justify-content: space-between;
  align-items: center;

  .title {
    font-family: YouSheBiaoTiHei;
    font-size: 30px;
  }

  .tip {
    margin-left: 15px;
    font-size: 14px;
  }
}

.main-box {
  width: calc(100% - 30px);
  height: calc(100% - 104px);
  overflow: auto;
  padding: 0 15px;
}

::v-deep .card {
  border-radius: 15px;
  margin-bottom: 15px;
  // &:first-child {
  //   margin-top: 0;
  // }

  .el-card__body {
    padding: 12px;
    width: calc(100% - 24px);
    height: 100%;
  }
}

.my-info {
  .handle-box {
    flex-shrink: 0;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .user-list {
      .user {
        color: #165dff;
        padding: 5px 0;
        border-bottom: 2px solid #165dff;
      }
    }

    .family {
      display: flex;
      align-items: center;
      color: #c8c8c8;
      cursor: pointer;

      .svg-icon.add {
        font-size: 20px;
      }
    }
  }

  .info-box {
    width: 100%;
    margin-top: 15px;
    display: flex;
    flex-direction: column;
    align-items: center;

    .avatar-box {
      flex-shrink: 0;
      width: 100%;
      display: flex;
      justify-content: space-evenly;
      align-items: center;

      .avatar {
        width: 140px;
        height: 140px;
        background-image: url('~@/assets/images/insuranceRecommend/avatar.png');
        background-repeat: no-repeat;
        background-size: 100% 100%;
      }

      .my-base {
        display: flex;
        flex-direction: column;
        align-items: center;

        .name {
          font-size: 18px;
          color: #7f7f7f;
          text-align: center;
          margin-bottom: 10px;
        }

        .link {
          font-size: 24px;
          font-weight: bold;
          color: #494949;
        }
      }
    }

    .my-claims {
      flex-shrink: 0;
      margin-top: 10px;
      padding: 15px;
      border-radius: 10px;
      border: 1px solid #dfe5f166;
      display: flex;
      align-items: center;

      .amount-box {
        font-size: 18px;
        margin-right: 20px;

        .label {
          color: #a5b4cb;
        }

        .value {
          color: #141736;
        }
      }

      .calculation-btn {
        padding: 0px 25px;
        border-radius: 10px;
        background-color: #0177fb;
        height: 40px;
        line-height: 40px;
        color: #fff;
        font-size: 18px;
        cursor: pointer;

        &.disable {
          cursor: not-allowed;
          background-color: #a0cfff;
        }
      }
    }
  }
}

.insurance-data {
  display: flex;
  flex-direction: column;

  .chart-box {
    // flex: 1;
    // min-height: 200px;
    // height: 308px;
    height: 295px;
    margin-top: 10px;

    // margin-bottom: 15px;
    .chart {
      height: 100%;
      width: 100%;
    }
  }

  .insurance-box {
    .legend-box {
      display: flex;
      justify-content: space-around;
      // margin-bottom: 20px;

      .legend-item {
        position: relative;
        margin-left: 16px;

        &::before {
          content: '';
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          position: absolute;
          left: -16px;
          top: 50%;
          transform: translateY(-50%);
        }

        &.full-protection::before {
          background: #fbb940;
        }

        &.partial-protection::before {
          background: #9dc6fb;
        }

        &.not-protection::before {
          background: #fed2d3;
        }
      }
    }

    .insurance-item {
      width: 50%;
      display: inline-flex;
      align-items: center;
      font-size: 18px;
      cursor: pointer;
      margin-top: 20px;

      // &:last-child {
      //   margin-top: 0px;
      // }

      &.full {
        .value {
          color: #ffc834;
        }

        .icon {
          background-image: url('@/assets/images/insuranceRecommend/insurance-full-icon.png');
        }
      }

      &.partial {
        .value {
          color: #165dff;
        }

        .icon {
          background-image: url('@/assets/images/insuranceRecommend/insurance-partial-icon.png');
        }
      }

      .icon {
        flex-shrink: 0;
        width: 60px;
        height: 60px;
        margin-right: 10px;
        background-image: url('@/assets/images/insuranceRecommend/insurance-not-icon.png');
        background-repeat: no-repeat;
        background-size: 100% 100%;
      }

      .text-box {
        font-size: 16px;
      }

      .value {
        color: #d6d6d6;
      }
    }
  }
}

.insurance-recommend {
  // flex: 1;
  // width: 100%;
  // height: 100%;
  // min-height: calc(100vh - 124px);
  // max-height: calc(100vh - 124px);

  ::v-deep .el-card__body {
    // padding: 20px;
    // padding-top: 15px;
    // min-height: calc(100vh - 124px);
    // max-height: calc(100vh - 124px);
  }

  .card-title {
    flex-shrink: 0;
    padding-bottom: 10px;
    margin-bottom: 10px;
    border-bottom: 1px solid rgba(227, 234, 244, 0.8);
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #165dff;

    .title {
      font-size: 20px;
      font-weight: bold;
    }

    .svg-icon.back {
      font-size: 26px;
      cursor: pointer;
    }
  }

  .content-box {
    // min-height: calc(100vh - 226px);
    // max-height: calc(100vh - 226px);
    // min-height: calc(100vh - 164px);
    // max-height: calc(100vh - 164px);
    // min-height: calc(100vh - 210px);
    // max-height: calc(100vh - 210px);
    // flex: 1;
    width: 100%;
    // overflow: auto;

    .result-box {
      // height: 100%;
      // min-height: calc(100vh - 164px);
      // max-height: calc(100vh - 164px);
      // min-height: calc(100vh - 210px);
      // max-height: calc(100vh - 210px);
      width: 100%;
      overflow: auto;
    }

    .analyze-box {
      width: 100%;

      .title {
        font-size: 18px;
        margin-bottom: 10px;

        .svg-icon.analyze {
          font-size: 24px;
          margin-right: 5px;
        }

        .analyze-loading {
          margin-left: 15px;
          font-size: 16px;
          color: #555;
        }
      }

      ::v-deep .analyze-process {
        border: none;
        // margin-right: 20px;
        margin-bottom: 20px;

        // max-height: 250px;
        .el-collapse-item__content {
          padding-bottom: 15px;
        }

        .el-collapse-item__header {
          border: none;
          align-items: start;
        }

        .el-collapse-item__arrow {
          margin: 18px 0px 0 5px;
          font-size: 15px;
          color: #555;
        }
      }

      .analyze-result {
        max-height: 250px;
        // width: 100%;
        // max-width: 90%;
        // margin-right: 20px;
        color: #5c5c5c;
        padding: 0 15px;
        border-radius: 14px;
        background-color: #f3f3f3;
        overflow: hidden;

        &.process {
          margin-right: 0;
          padding: 0;
          border-radius: 0px;
          background-color: #fff;

          .content {
            margin: 0 !important;
          }

          .row {
            border-left: 2px solid #e5e5e5 !important;
            color: #8b8b8b;
            font-size: 15px;

            &::before {
              content: none !important;
            }
          }
        }

        .content {
          max-height: 220px;
          width: 100%;
          margin: 15px 0;
          overflow: auto;

          .row {
            position: relative;
            margin-right: 10px;
            padding-left: 15px;
            margin-left: 5px;
            border-left: 1px solid #fff;
            padding-bottom: 15px;

            &:last-child {
              padding-bottom: 0px;
            }

            &::before {
              content: '';
              display: inline-block;
              width: 12px;
              height: 12px;
              background: #165dff;
              border-radius: 50%;
              position: absolute;
              left: -6px;
              top: 6px;
            }
          }
        }
      }
    }

    .chat-box {
      .msg-row {
        // width: 100%;
        margin: 20px 0;
        // margin-right: 20px;
        // padding: 0px 10px;
        display: flex;
        justify-content: start;
        font-size: 16px;

        &.right {
          justify-content: end;
          flex-direction: row-reverse;
        }

        .user-info {
          display: flex;
          align-items: start;

          .avatar {
            width: 35px;
            height: 35px;
            margin-right: 15px;
          }
        }

        .content {
          // max-width: 90%;
          width: 100%;
          padding: 15px;
          border-radius: 10px;
          background-color: #f6f6f6;
          white-space: pre-line;
          position: relative;

          &:has(i) {
            width: auto;
          }

          &::before {
            content: ' ';
            position: absolute;
            left: -12px;
            top: 9px;
            margin-bottom: 3px;
            width: 0;
            height: 0;
            border-bottom: 9px solid transparent;
            border-top: 9px solid transparent;
            border-right: 12px solid #f6f6f6;
          }

          .tip {
            color: #165dff;
            margin-right: 10px;
          }

          .content-data {
            width: 100%;
            overflow-x: auto;
            white-space: normal; // 允许表格内文字换行（可选）
          }

          ::v-deep p {
            margin: 0;
          }

          &.user {
            background-color: #c5cee0;
          }

          // &:has(.table),
          // &:has(.chart) {
          //   width: 100%;
          // }
          .table,
          .chart,
          .insurance-compare-box,
          .solution-box {
            margin-block-start: 15px;
            width: 100%;
            // width: calc(100% - 60px);
          }

          // height: 300px;
          ::v-deep .el-table {
            width: 100%;
            ::v-deep .el-table__cell {
              font-size: 15px;
            }
          }

          .insurance-compare-box {
            .compare-row {
              border-bottom: 1px solid #d8d8d8;
              padding-bottom: 50px;
              margin-bottom: 50px;

              &:last-child {
                border: none;
                padding-bottom: 0px;
                margin-bottom: 0px;
              }
            }

            .compare-title {
              font-size: 18px;
              color: #165dff;
              margin-bottom: 10px;
            }

            .compare-content {
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              position: relative;

              .vs {
                // position: absolute;
                text-align: center;
                font-size: 3rem;
                font-weight: bold;
                // left: 50%;
                // top: 50%;
                // transform: translate(-50%, -50%);
              }

              .insurance-box {
                // width: 45%;
                width: 100%;

                // min-width: 350px;
                &.length1 {
                  width: 100%;
                }

                .compare-tip {
                  .title {
                    font-size: 16px;
                    color: #165dff;
                    margin-bottom: 2px;
                  }
                  font-size: 14px;
                  color: #3d3d3d;
                  margin-bottom: 5px;
                }
              }

              .insurance-item {
                display: inline-block;
                // width: 100%;
                width: calc(100% - 30px);
                border-radius: 5px;
                border: 1px solid #e5e8ef;
                background-color: #fff;
                padding: 15px;
                margin-bottom: 10px;
                cursor: pointer;

                .base-info {
                  display: flex;
                  margin-bottom: 15px;

                  .img-box {
                    flex-shrink: 0;
                    width: 110px;
                    height: 110px;
                    margin-right: 15px;
                    background-image: url('~@//assets/images/insuranceRecommend/insurance-img.png');
                    background-repeat: no-repeat;
                    background-size: 100% 100%;
                  }

                  .text-box {
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;

                    .name {
                      font-size: 20px;
                    }

                    .company-name {
                      font-size: 16px;
                      color: #444;
                    }

                    .price {
                      font-size: 20px;
                      color: #ff0000;
                    }
                  }
                }

                .more-info {
                  // flex: 1;
                  display: flex;
                  width: 100%;

                  .info-item {
                    flex: 1;
                    text-align: center;
                    font-size: 18px;
                    border-right: 1px solid #d8d8d8;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;

                    &:last-child {
                      border: none;
                    }

                    .label {
                      color: #c8c8c8;
                    }
                  }
                }
              }
            }
          }

          .solution-box {
            .tab-box {
              width: calc(100% - 20px);
              padding: 0 10px;
              display: flex;

              .tab-item {
                font-size: 15px;
                padding: 8px;
                color: #909399;
                // background-color: #ecf5ff;
                background-color: #fff;
                border: 1px solid #c8c8c8;
                border-right: none;
                cursor: pointer;

                &.active {
                  background-color: #0177fb;
                  color: #fff;
                }

                &:first-child {
                  border-top-left-radius: 10px;
                }

                &:last-child {
                  border-top-right-radius: 10px;
                  border-right: 1px solid #c8c8c8;
                }
              }
            }

            .solution-content-box {
              .title-box {
                border-top-left-radius: 10px;
                border-top-right-radius: 10px;
                padding: 8px 20px;
                width: calc(100% - 40px);
                display: flex;
                justify-content: space-between;
                align-items: center;
                background-image: url('~@/assets/images/insuranceRecommend/solution-title-box_BG.png');
                background-size: auto 100%;
                font-size: 15px;

                .company-name {
                  color: #ffffff;
                  padding: 5px 12px;
                  border-radius: 42px;
                  background: linear-gradient(180deg, #0177fb 0%, rgba(216, 216, 216, 0) 100%);
                }

                .amount {
                  // text-shadow: 1px 0 #fff, -1px 0 #fff, 0 1px #fff, 0 -1px #fff, 1px 1px #fff, -1px -1px #fff,
                  //   1px -1px #fff, -1px 1px #fff;
                  // color: #ff0000;
                  padding: 5px 12px;
                  border-radius: 42px;
                  background: linear-gradient(180deg, #ff0000 0%, rgba(216, 216, 216, 0) 100%);
                  color: #fff;

                  .num {
                    font-size: 20px;
                  }
                }
              }

              .data-box {
                padding: 20px;
                background-color: #fff;

                .empty-data {
                  width: 100%;
                  text-align: center;
                }

                .data-item {
                  margin-bottom: 15px;

                  &:last-child {
                    margin-bottom: 0px;
                  }
                }

                .data-title {
                  padding-left: 10px;
                  border-left: 3px solid #0177fb;
                  // line-height: 16px;
                  // height: 16px;
                }

                .data {
                  margin: 0 15px;
                  font-size: 15px;
                  color: #7f7f7f;

                  &:nth-child(2) {
                    margin-top: 15px;
                  }
                }

                .data-children {
                  font-size: 15px;
                  padding: 15px 0;
                  margin: 0 15px;
                  border-bottom: 1px solid #d8d8d8;

                  &:last-child {
                    border-bottom: none;
                  }

                  .data-children-label {
                    color: #0177fb;
                  }

                  .data-children-data {
                    color: #7f7f7f;
                  }

                  &:has(span) {
                    // padding: 2px 0;
                    // border-bottom: none;

                    // &:nth-child(2) {
                    //   padding-top: 15px;
                    // }

                    // &:last-child {
                    //   padding-bottom: 15px;
                    // }

                    .data-children-label {
                      margin-right: 10px;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
